package com.hengyue.controller.system;

import com.hengyue.common.constants.Constants;
import com.hengyue.common.core.result.AjaxResult;
import com.hengyue.security.modle.LoginUser;
import com.hengyue.security.service.SysLoginService;
import com.hengyue.security.service.TokenService;
import com.hengyue.security.utils.SecurityUtils;
import com.hengyue.system.domain.dto.LoginBody;
import com.hengyue.system.domain.entity.SysMenu;
import com.hengyue.system.domain.entity.SysUser;
import com.hengyue.system.service.ISysMenuService;
import com.hengyue.system.service.ISysPermissionService;
import com.hengyue.system.service.ISysRoleService;
import com.hengyue.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author Hengyue
 */
@RestController
public class LoginController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysPermissionService permissionService;


    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);

        return ajax;
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getSysUser();
        /*
          获取角色roleKey集合
         */
        Set<String> roles = permissionService.getRolePermission(user);
        // 获取权限
        Set<String> permissions = permissionService.getMenuPermission(user);
        // 刷新token,更新缓存中的loginUser
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
